{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Watch a Smart Agent!"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 1.Start the Environment for Trained Agent"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "device:  cuda\n",
      "state_size:  24 , action_size:  4 , action_high:  1.0\n"
     ]
    }
   ],
   "source": [
    "import numpy as np\n",
    "import torch\n",
    "import gym\n",
    "import argparse\n",
    "import os\n",
    "import time\n",
    "\n",
    "from TwinDelay import TD3\n",
    "\n",
    "env = gym.make('BipedalWalker-v2')\n",
    "\n",
    "# Set seeds\n",
    "seed = 12345\n",
    "env.seed(seed)\n",
    "torch.manual_seed(seed)\n",
    "np.random.seed(seed)\n",
    "\n",
    "state_size = env.observation_space.shape[0]\n",
    "action_size=env.action_space.shape[0]\n",
    "action_high= float(env.action_space.high[0])\n",
    "print('state_size: ', state_size, ', action_size: ', action_size, ', action_high: ', action_high)\n",
    "    \n",
    "agent = TD3(state_dim=state_size, action_dim=action_size, max_action=action_high)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2. Prepare Load"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "def load(agent, dir, prefix):\n",
    "    agent.actor.load_state_dict(\n",
    "        torch.load(os.path.join(dir,'%s_actor.pth' % prefix)))\n",
    "    agent.critic.load_state_dict(\n",
    "        torch.load(os.path.join(dir,'%s_critic.pth' % prefix)))\n",
    "    agent.actor_target.load_state_dict(\n",
    "        torch.load(os.path.join(dir,'%s_actor_t.pth' % prefix)))\n",
    "    agent.critic_target.load_state_dict(\n",
    "        torch.load(os.path.join(dir,'%s_critic_t.pth' % prefix)))\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 3. Prepare Player"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "from collections import deque\n",
    "import os\n",
    "\n",
    "def play(env, agent, n_episodes):\n",
    "    state = env.reset()\n",
    "    \n",
    "    scores_deque = deque(maxlen=100)\n",
    "    scores = []\n",
    "\n",
    "    for i_episode in range(1, n_episodes+1):\n",
    "        state = env.reset()        \n",
    "        score = 0\n",
    "        \n",
    "        time_start = time.time()\n",
    "        \n",
    "        while True:\n",
    "            action = agent.select_action(np.array(state))\n",
    "            env.render()\n",
    "            next_state, reward, done, _ = env.step(action)\n",
    "            state = next_state\n",
    "            score += reward\n",
    "            if done:\n",
    "                break \n",
    "\n",
    "        s = (int)(time.time() - time_start)\n",
    "        \n",
    "        scores_deque.append(score)\n",
    "        scores.append(score)\n",
    "\n",
    "        print('Episode {}\\tAverage Score: {:.2f},\\tScore: {:.2f} \\tTime: {:02}:{:02}:{:02}'\\\n",
    "                  .format(i_episode, np.mean(scores_deque), score, s//3600, s%3600//60, s%60))  \n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 3. Load and Play: Score = 293"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Episode 1\tAverage Score: 293.95,\tScore: 293.95 \tTime: 00:00:18\n",
      "Episode 2\tAverage Score: 294.16,\tScore: 294.37 \tTime: 00:00:12\n",
      "Episode 3\tAverage Score: 239.93,\tScore: 131.47 \tTime: 00:00:10\n",
      "Episode 4\tAverage Score: 253.46,\tScore: 294.04 \tTime: 00:00:12\n",
      "Episode 5\tAverage Score: 261.49,\tScore: 293.63 \tTime: 00:00:12\n"
     ]
    }
   ],
   "source": [
    "load(agent, 'dir_chk', 'checkpoint_293')\n",
    "play(env, agent, n_episodes=5)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 4. Load and Play: Score = 300.5,  training time = 9h 44m"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Episode 1\tAverage Score: 304.02,\tScore: 304.02 \tTime: 00:00:12\n",
      "Episode 2\tAverage Score: 304.14,\tScore: 304.26 \tTime: 00:00:12\n",
      "Episode 3\tAverage Score: 303.97,\tScore: 303.62 \tTime: 00:00:12\n",
      "Episode 4\tAverage Score: 304.11,\tScore: 304.54 \tTime: 00:00:12\n",
      "Episode 5\tAverage Score: 304.08,\tScore: 303.94 \tTime: 00:00:12\n"
     ]
    }
   ],
   "source": [
    "load(agent, 'dir_chk', 'chpnt_88seed_300-5sc_9h44m')\n",
    "play(env, agent, n_episodes=5)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 5. Load and Play: Score = 306"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Episode 1\tAverage Score: 304.04,\tScore: 304.04 \tTime: 00:00:12\n",
      "Episode 2\tAverage Score: 305.21,\tScore: 306.38 \tTime: 00:00:11\n",
      "Episode 3\tAverage Score: 305.97,\tScore: 307.49 \tTime: 00:00:11\n",
      "Episode 4\tAverage Score: 306.36,\tScore: 307.53 \tTime: 00:00:11\n",
      "Episode 5\tAverage Score: 306.41,\tScore: 306.58 \tTime: 00:00:11\n"
     ]
    }
   ],
   "source": [
    "load(agent, 'dir_chk', 'checkpoint_306')\n",
    "play(env, agent, n_episodes=5)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "env.close()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
